﻿using System;
using NHibernate;

namespace FinancePortal.Business.Infraestructure
{
    public class UnitOfWork : IUnitOfWork
    {
        private ITransaction _transaction;
        //private ISession _session;

        public UnitOfWork(NHibernateHelper helper)
        {
            CurrentSession = helper.SessionFactory.OpenSession();
        }

        public void BeginTransaction()
        {
            _transaction = CurrentSession.BeginTransaction();
        }

        public ISession CurrentSession
        {
            get;
            set;
        }

        public void Dispose()
        {
            //if (!_transaction.WasCommitted)
            //{
            //    _transaction.Rollback();
            //    throw new InvalidOperationException("Transation non commited on disposal");
            //}
            if (_transaction != null)
                _transaction.Dispose();

            CurrentSession.Dispose();
            //_session.Dispose();
            //_session = null;
        }

        public void Commit()
        {
            if (!_transaction.IsActive)
                throw new InvalidOperationException("No active transation");

            _transaction.Commit();
        }

        public void Rollback()
        {
            if (_transaction.IsActive)
                _transaction.Rollback();
        }
    }
}
